const util = require('util')
const { wx } = require('../../config/config');
const { AuthFailed } = require('../../core/http-exception')
const { User } = require('../models/user')
const { generateToken } = require('../../core/util')
const { Auth } = require('../../middlewares/auth')
const axios = require('axios')

class WxManager {
    static async codeToToken(code) {
        const url = util.format(wx.loginUrl,
            wx.appId,
            wx.appSecret,
            code);

        const result = await axios.get(url)
        if (result.status !== 200) {
            throw new AuthFailed('oppid 获取失败')
        }
        const errcode = result.data.errcode;
        const errmsg = result.data.errmsg;
        if (errcode && errcode !== 0) {
            throw new AuthFailed('oppid 获取失败' +errcode+':'+ result.data.errmsg)
        }
        const openid = result.data.openid
        // 查询用户是否存在
        let user = await User.getUserByOpenId(openid);
        if (!user) {
            user = await User.registerByOpenId(openid)
        }

        return generateToken(user.id, Auth.USER)

        // if(errcode == -1){
        //     throw new AuthFailed('系统繁忙，此时请开发者稍候再试')
        // }
        // if(errcode == 40029){
        //     throw new AuthFailed('code 无效')
        // }
        // if(errcode == 45011){
        //     throw new AuthFailed('频率限制，每个用户每分钟100次')
        // }
    }
}

module.exports = {
    WxManager
}